<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.bookName"
        placeholder="图书名称"
        clearable
        style="width: 200px; margin-right: 20px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.author"
        placeholder="图书作者"
        clearable
        style="width: 130px; margin-right: 20px"
        class="filter-item"
      >
      </el-input>
      <el-select
        v-model="listQuery.bookType"
        placeholder="图书类型"
        clearable
        class="filter-item"
        style="width: 140px; margin-right: 20px"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        style="margin-right: 5px"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-right: 5px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload(1)"
      >
        导出本页
      </el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload(0)"
      >
        导出所有
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="bookList"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      :row-class-name="tableRowClassName"
    >
      <!-- 图书id -->
      <el-table-column align="center" label="ID" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <!-- 创建时间 -->
      <el-table-column align="center" label="创建时间" width="95">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <!--书名  -->
      <el-table-column label="图书名称" width="320" align="center">
        <template slot-scope="scope">
          {{ scope.row.bookName }}
        </template>
      </el-table-column>
      <!-- 作者 -->
      <el-table-column label="作者" width="90" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
      </el-table-column>
      <!-- 类型 -->
      <el-table-column label="书籍类型" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.bookTypeStr }}
        </template>
      </el-table-column>
      <!-- 图书价格 -->
      <el-table-column
        class-name="status-col"
        label="价格"
        width="90"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.price }}
        </template>
      </el-table-column>
      <!-- 封面图片 -->
      <el-table-column
        align="center"
        prop="coverUrl"
        label="封面图片"
        width="100"
      >
        <template slot-scope="scope">
          <el-image
            :src="scope.row.coverUrl"
            :preview-src-list="[scope.row.coverUrl]"
          >
          </el-image>
        </template>
      </el-table-column>
      <!-- 图书操作 -->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="editBook(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteBook(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-size="10"
      layout="total, prev, pager, next"
      :total="total"
    >
    </el-pagination>
    <!--    更新图书-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="50%"
      top="10vh"
    >
      <el-form :model="row" :rules="rules" :ref="row">
        <el-form-item
          label="图书名称"
          :label-width="formLabelWidth"
          prop="bookName"
        >
          <el-input v-model="row.bookName" style="width: 50vh"></el-input>
        </el-form-item>
        <el-form-item
          label="图书价格"
          :label-width="formLabelWidth"
          prop="price"
        >
          <el-input v-model.number="row.price" style="width: 50vh"></el-input>
        </el-form-item>
        <el-form-item
          label="图书作者"
          :label-width="formLabelWidth"
          prop="author"
        >
          <el-input v-model="row.author" style="width: 50vh"></el-input>
        </el-form-item>
        <el-form-item
          label="图书类型"
          :label-width="formLabelWidth"
          prop="bookType"
        >
          <el-select
            v-model="row.bookType"
            filterable
            :placeholder="row.bookTypeStr"
            style="width: 50vh"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.symbol
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
<script>
// API
import {
  getList,
  updateBook,
  deleteBook,
  addBook,
  getAllBooks,
} from "@/api/table";
// message
import { notify, confirm, DEL, UPD, ADD, EXP } from "@/utils/message";
// transmit book type
import { transBookType } from "@/utils/book-type";
import { bookTypeOptions } from "@/utils";

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      bookList: null,
      allList: null, // 所有
      listLoading: true,
      dialogStatus: "",
      textMap: {
        create: "新增图书",
        update: "修改图书信息",
      },
      // 新增图书-规则
      rules: {
        bookName: [
          { required: true, message: "图书名称是必填项", trigger: "blur" },
        ],
        price: [
          {
            type: "number",
            required: true,
            message: "图书价格是必填项",
            trigger: "blur",
          },
        ],
        author: [
          { required: true, message: "图书作者是必填项", trigger: "blur" },
        ],
        bookType: [
          { required: true, message: "图书类型是必选项", trigger: "blur" },
        ],
      },
      dialogFormVisible: false, // 修改数据对话框，是否显示
      formLabelWidth: "120px",
      row: {}, // 回显数据
      options: bookTypeOptions,
      currentPage: 1,
      total: 0, // 数据总数
      // 查询条件
      listQuery: {
        bookName: undefined,
        author: undefined,
        bookType: undefined,
      },
      downloadLoading: false, // 是否下载中
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 条件查询
    handleFilter() {
      getList({
        book: this.listQuery,
        bookPage: {},
      }).then((response) => {
        notify(1, "刷新", "已展示符合搜索的图书数据");
        // 获取请求到的图书数据
        console.log(response);
        this.bookList = transBookType(response.data.data.books);
        this.total = response.data.data.total;
      });
    },
    // 点击新增
    handleCreate() {
      this.dialogStatus = "create";
      this.row = {}; // 清空
      this.dialogFormVisible = true;
    },
    // 执行新增操作（先执行校验规则）
    createData() {
      this.$refs[this.row].validate((valid) => {
        if (valid) {
          addBook(this.row)
            .then((res) => {
              notify(1, ADD, "成功添加一本书籍信息");
              this.fetchData();
            })
            .catch((err) => {
              notify(2, ADD, "网络繁忙");
            });
          this.dialogFormVisible = false;
        } else {
          notify(2, ADD, "你的输入数据格式有误");
          return false;
        }
      });
    },

    // 点击导出
    handleDownload(tag) {
      let bookList = null;
      notify(4, "正在查询数据并导出");
      if (tag == 1) {
        bookList = this.bookList; // 导出本页
      } else {
        this.getAll();
        setTimeout(() => {
          bookList = this.allList;
        }, 1000);
      }

      setTimeout(() => {
        this.downloadLoading = true;
        import("@/vendor/Export2Excel").then((excel) => {
          const tHeader = ["书名", "作者", "价格", "类型"];
          const filterVal = ["bookName", "author", "price", "bookTypeStr"];
          const data = this.formatJson(bookList, filterVal);
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: "当当书籍数据",
          });
          this.downloadLoading = false;
        });
        // this.$message({
        //   message: "导出成功",
        //   type: "success",
        // });
        notify(1, EXP);
      }, 2000);
    },

    // 导出-辅助
    formatJson(data, filterVal) {
      return data.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    // 查询所有数据，用于导出
    getAll() {
      getAllBooks()
        .then((res) => {
          this.allList = transBookType(res.data.data);
        })
        .catch((err) => {
          notify(2, EXP, "查询所有图书数据错误");
        });
    },
    // 点击页码切换
    handleCurrentChange(page) {
      this.currentPage = page; // 设置当前页码
      // 分页查询（带上筛选条件）
      getList({
        book: this.listQuery,
        bookPage: { page: page, pageSize: 10 },
      }).then((response) => {
        // 获取请求到的图书数据
        this.bookList = transBookType(response.data.data.books);
      });
    },
    // 获取所有图书信息
    fetchData() {
      this.listLoading = true;
      getList({ book: {}, bookPage: {} }).then((response) => {
        // 获取请求到的图书数据
        this.total = response.data.data.total;
        this.bookList = transBookType(response.data.data.books);
        this.listLoading = false;
      });
    },
    // 表格颜色
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 == 0) {
        return "success-row"; // "success-row"
      }
      return "";
    },
    // 编辑
    editBook(row) {
      this.row = { ...row }; // 复制对象
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
    },
    // 执行编辑事件
    updateData() {
      updateBook(this.row)
        .then((response) => {
          if (response.data.code == "200") {
            notify(1, UPD);
            this.fetchData();
          } else {
            notify(2, UPD, "网络开了点小差");
          }
        })
        .catch(() => notify(2, DEL, "发生错误了"));
      // 关闭弹框
      this.dialogFormVisible = false;
    },
    // 删除
    deleteBook(row) {
      confirm("此操作将永久删除该记录, 是否继续?")
        .then(() => {
          deleteBook([row.id])
            .then((response) => {
              if (response.data.code == "200") {
                notify(1, DEL);
                this.fetchData();
              } else {
                notify(2, DEL);
              }
            })
            .catch(() => notify(2, DEL, "发生错误了"));
        })
        .catch(() => {
          notify(3, DEL);
        });
    },
  },
};
</script>
